module IHelpers
  module ActiveRecord
    module Validations

      def self.included(base)
        base.extend ClassMethods
      end

      module ClassMethods

        # Taken from: http://marklunds.com/articles/one/312
        def validates_as_email(*attr_names)
          configuration = {
            :message   => :email,
            :with      => Format::EMAIL, # Requires simply_useful gem
          }
          configuration.update(attr_names.extract_options!)

          validates_format_of attr_names, configuration
        end

        # Taken from: http://marklunds.com/articles/one/312
        def validates_as_phone(*attr_names)
          configuration = {
            :message => :phone,
            :on => :save
          }
          configuration.update(attr_names.extract_options!)

          validates_each(attr_names, configuration) do |record, attr_name, value|
            n_digits = value.scan(/[0-9]/).size
            valid_chars = (value =~ /^[+\/\-() 0-9]+$/)
            if !(n_digits > 5 && valid_chars)
              record.errors.add(attr_name, configuration[:message])
            end
          end
        end

        def validates_as_immutable(*attr_names)
          options = attr_names.extract_options!
          options.reverse_merge!({:message => :immutable, :allow_change_from_nil => false, :on => :save})

          validates_each(attr_names, options) do |record, attr_name, value|
            if !record.new_record? && record.send("#{attr_name}_changed?") &&
                !(options[:allow_change_from_nil] && record.send("#{attr_name}_was").nil?)
              record.errors.add(attr_name, options[:message])
            end
          end
        end
  
      end
    end
  end
end